﻿using System;
using System.Globalization;

namespace Esponce.Common
{
	/// <summary>
	/// ISO 8601 format for date and time
	/// http://www.ietf.org/rfc/rfc3339.txt
	/// http://www.w3.org/TR/NOTE-datetime
	/// http://en.wikipedia.org/wiki/ISO_8601
	/// </summary>
	internal class ISO8601
	{
		public const string DateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";

		/// <summary>
		/// Converts date and time to ISO 8601 string: yyyy-MM-ddTHH:mm:ssZ
		/// </summary>
		/// <param name="dt"></param>
		/// <returns></returns>
		public static string GetString(DateTime? dt)
		{
			return dt != null ? dt.Value.ToString(DateTimeFormat) : null;
		}

		/// <summary>
		/// Converts ISO 8601 string to date and time. ISO 8601 defines formatting "yyyy-MM-ddTHH:mm:ssZ"
		/// </summary>
		/// <param name="iso">String formatted as "yyyy-MM-ddTHH:mm:ssZ"</param>
		/// <returns>Returns date and time.</returns>
		public static DateTime? GetDateTime(string iso)
		{
			DateTime dt;
			if (DateTime.TryParseExact(iso ?? "", DateTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
			{
				return dt;
			}
			return null;
		}
	}
}
